/**
 * 呼叫系统插件
 */
;(function () {
	var callObj = $("img[call]");
	callObj.css("cursor", "pointer");
	callObj.attr("title", "拨号");
	$.fn.extend({
		call :function(){
			callCoreEvent(this);
		}
	});
	/**
	 * 点击电话图标 进行呼叫
	 */
	callObj.off('click').on('click', function () {
		//兼容jqgrid
		var type = $(this).attr("call");
		if(type == "book") return;
		callCoreEvent(this);
	});
	
	var callCoreEvent = function(o){
		if (callObj.attr("disabled") != undefined) return;
		var currentObj = $(o);
		var anjianstauts = currentObj.attr("anjianstauts");//案件状态
		if (anjianstauts == 0) {
			message("待催收案件不能进行电话催收!");
			return;
		}
		var mType = currentObj.attr("mType");//联系类型
		var uContactsInfoId = currentObj.attr("uContactsInfoId");//联系人id
		var callLoanNid = currentObj.attr("callLoanNid");//催收编号
		var borrowNid = currentObj.attr("borrowNid");//
		var anjianUserId = currentObj.attr("anjianUserId");//案件
		
		//通讯录 人名和手机
		var userName  = currentObj.attr("userName");
		var recordMobile  = currentObj.attr("recordMobile");
		
		log("参数", anjianstauts + "-" + uContactsInfoId + "-" + mType + "-" + callLoanNid + "-" + borrowNid + "-" + anjianUserId);
		//获取分机号
		$.httpUtil_GET("call/getMachineNum", function (data) {
			log("分机号", data);
			if (!data) {
				message("你未分配分机号，请联系管理员！");
				return;
			}
			//获取被呼叫人信息
			getCalled(uContactsInfoId, mType, callLoanNid, borrowNid, anjianUserId,userName,recordMobile);
		});
	}
	
	/**
	 * 获取被呼叫人信息
	 * @param uContactsInfoId 联系人id
	 * @param mType {m1:联系方式1，m2:联系方式2，m3:联系方式3，mc:公司号码}
	 * @param callLoanNid 催收编号
	 */
	var getCalled = function (uContactsInfoId, mType, callLoanNid, borrowNid, anjianUserId,userName,recordMobile) {
		var callInfoObj = {
			uContactsInfoId: uContactsInfoId, callLoanNid: callLoanNid, borrowNid: borrowNid, anjianUserId: anjianUserId
			,userName:userName,recordMobile:recordMobile
		};
		log("callInfoObj", callInfoObj);
		$.httpUtil_GET("call/getCalled", callInfoObj,
			function (data) {
				log("被呼叫人信息", data);
				var callServiceIp = data.callServiceIp;
				// window.callRecordDownloadFileIp = "http://" + callServiceIp + "/uncall_api/downloadFile.php?f_path=";
				// window.callRecordFilePageIp = "http://" + callServiceIp + "/uncall_api/ccplay/play/player/index.php?files=";
				log("参数平台callIP", callServiceIp);
				if (callServiceIp != undefined || callServiceIp != "") {
					onClickCall(data, mType,callInfoObj);
				} else {
					log("未获取到参数平台callIP", callServiceIp);
				}
			}
		);
	};
	
	
	/**
	 * 弹出通话页面
	 */
	var openTellPage = function (data, mType,callInfoObj) {
		var interval, layerContentWidth, layerContentHeight;
		var layerWidth, layerHeight;
		var menu = $.getCurrentTabName();
		//页面层
		layer.open({
			type: 1,
			title: "通话录音页面",
			skin: 'layui-layer-rim', //加上边框
			area: ['450px', '560px'], //宽高
			btn: ["保存"],
			btnAlign: 'c',
			shade: 0,
			resize: false,
			// closeBtn:0,
			anim: 4,
			maxmin: true,
			content: getPage(data, mType,callInfoObj),//组装页面
			success: function (layero, index) {//弹出页成功出现的回调
				//禁止右侧菜单
				$.lockMenu(menu);
				layerWidth = $(".layui-layer").width();
				layerHeight = $(".layui-layer").height();
				layerContentWidth = $(".layui-layer-content").width();
				layerContentHeight = $(".layui-layer-content").height();
				callObj.css("cursor", "").addClass("notAllowed").attr("disabled", "disabled");
				//弹屏获取uid 以便于获取录音,最后保存数据
				interval = setInterval(function () {
					popEvent();
				}, 3000);
			},
			restore: function () {
				$(".layui-layer-content").css({"height": layerContentHeight, "width": layerContentWidth});
				$(".layui-layer").css({"height": layerHeight + 11, "width": layerWidth + 11});
			},
			end: function () {//弹出层销毁，刷新短信通话列表
				//放开右侧菜单
				$.unLockMenu(menu);
				callObj.removeClass("notAllowed").css("cursor", "pointer").removeAttr("disabled");
				clearInterval(interval);
				$("#cRecord").refreshGridView();//刷新催计列表
				$("#messageAndTell").refreshGridView();//刷新通话短信列表
			},
			cancel: function(index, layero){
				if(confirm('数据将不会被保存，确定要关闭么？[此功能支持是在通话状态下的挂断,非接通情况需通过话筒挂断]')){
					$.getJSON("call/hangUp",function(data){
						log("挂断电话",data);
						layer.close(index);
					});
				}
				return false;
			},
			yes: function (index, layero) {//保存按钮事件
				clearInterval(interval);
				var uid = $("input[uid]").val();
				//同步催收记录
				var callLoanLog = {
					callLoanNid: data.callLoanNid,
					callUser: data.callUser,
					callShip: $("#r").val(),
					//催收方式 电话
					callType: "1",
					callResult: $("#re").val(),
					toRealName: data.realName,
					linkManName: callInfoObj.borrowNid == "book" ? callInfoObj.userName : data.contUserName,
					toMobile: callInfoObj.borrowNid == "book" ? callInfoObj.recordMobile : (data[mType] ? data[mType] : ""),
					promiseRepaymentDay: $("#returnDate").val(),
					callResultDesc: $("textarea[name='remark']").val()
				};
				log("保存催收记录数据：", callLoanLog);
				if ($("#r").val() == "") {
					message("请选择催收关系");
					return;
				}
				if ($("#re").val() == "") {
					message("请选择催收结果");
					return;
				}
				if ($("textarea[name='remark']").val().length > 200) {
					message("催收结果说明最多允许200个字符");
					return;
				}
				//通话完该话机处于空闲获取录音
				getExtenStatus(uid, data, mType, index,callLoanLog,callInfoObj);
				
			}
		});
	}
	
	/**
	 * 点击拨号
	 * @param totel 被叫号码
	 */
	var onClickCall = function (para, mType,callInfoObj) {
		//针对号码带杠
		var toTel = callInfoObj.borrowNid == "book" ? callInfoObj.recordMobile : para[mType];//book 代表是通讯录的号码
		if (/-/.test(toTel)) {
			toTel = (para[mType]).replace(/-/g, "");
		}
		log("点击拨号开始", "+++++++++");
		$.httpUtil_POST("call/onClickCall", {toTel: toTel}, function (data) {
			log("点击拨号", data);
			if (!isSuccessCall1(data)) {
				message("呼叫异常！");
				return;
			}
			openTellPage(para, mType,callInfoObj);
		});
	}
	
	/**
	 * 挂断
	 */
	var hangUp = function () {
		$.httpUtil_GET("call/hangUp", function (data) {
			if (!isSuccessCall2(data)) {
				message("挂断异常！");
				return;
			}
		});
	}
	
	
	/**
	 * 保存通话记录
	 * @param callLoanConverseInfo
	 */
	var saveCall = function (callLoanConverseInfo, index) {
		$.httpUtil_POST("call/saveCall", callLoanConverseInfo, function (data) {
			log("保存通话记录 f返回", data);
			!~~data ? message("保存通话记录异常！") : (layer.close(index), message("保存成功!", {icon: 1}));
		});
	};
	
	/**
	 * 保存催收记录
	 * @param callLoanLog
	 */
	var saveCallLoanLog = function (callLoanLog) {
		$.httpUtil_POST("call/saveCallLoanLog", callLoanLog, function (data) {
			log("保存催收记录 返回", data);
			if (!~~data) {
				message("保存催收记录失败，请转手动添加催收记录！");
				consoles("保存催收记录失败，请转手动添加催收记录！");
			}
		});
	}
	
	/**
	 * 弹屏     --获取uid
	 */
	var popEvent = function () {
		$.httpUtil_POST("call/popEvent", function (data) {
			var uid = isSuccessCall3(data) ? data.uid : "";
			if (!isSuccessCall3(data)) {
				message("弹屏异常！");
				return;
			}
			var uid = $("input[uid]").val();
			if (!uid) {
				$("input[uid]").val(data.uid);
			}
		});
	}
	
	/**
	 * 分机状态
	 * status:状态、其中（0 空闲、8 振铃、4 不在线 、1 通话中    11 示忙）
	 */
	var getExtenStatus = function (uid, para, mType, index,callLoanLog,callInfoObj) {
		$.httpUtil_POST("call/getExtenStatus", function (data) {
			if (!isSuccessCall3(data) && data.status == undefined) {
				message("获取分机状态异常！");
				return;
			}
			var status = data.status;
			//空闲 获取 录音
			if (status == "0") {
				//同步催收记录
				saveCallLoanLog(callLoanLog);
				getRecording(uid, para, mType, index,callInfoObj)
			} else {
				message("请挂断后，再进行保存！");
			}
		});
	}
	
	/**
	 * 获取录音文件名
	 * @param uid
	 */
	var getRecording = function (uid, para, mType, index,callInfoObj) {
		$.httpUtil_POST("call/getRecording", {uid: uid}, function (data) {
			if (!isSuccessCall3(data)) {
				message("获取录音文件名异常！");
				return;
			}
			//录音文件名
			var callInfo = data.files;
			var callLoanConverseInfo = {
				callLoanNid: para.callLoanNid,
				callUser: para.callUser,
				toRealNameType: para.contType,
				toRealName: callInfoObj.borrowNid == "book" ? callInfoObj.userName : para.contUserName,
				toMobile: callInfoObj.borrowNid == "book" ? callInfoObj.recordMobile : (para[mType] ? para[mType] : ""),
				callInfo: callInfo,
				remark: $("textarea[name='remark']").val()
			};
			log("保存数据", callLoanConverseInfo);
			//保存通话
			saveCall(callLoanConverseInfo, index);
		});
	}
	
	/**
	 * 组装页面
	 */
	var getPage = function (data, mType,callInfoObj) {
        console.log(callInfoObj.borrowNid)
        console.log(callInfoObj.borrowNid == "top")
		var page = [
			"<input type='hidden' uid />",
			"<table class='table' id='callTable'>",
			"<tr>",
			"<td>催收对象：</td>",
			"<td>" + data.realName + "</td>",
			"</tr>",
			"<tr>",
			"<td>联系人：</td>",
			"<td>" + (callInfoObj.borrowNid == "book" ? callInfoObj.userName : data.contUserName) + "</td>",
			"</tr>",
			"<tr>",
			"<td>催收关系：</td>",
			callInfoObj.borrowNid != "book" ?
				"<td><select id=\"r\" style=\"width: 150px;\"><option value=\"\">请选择</option><option value=\"1\">本人</option><option value=\"2\">亲属</option><option value=\"3\">同事</option><option value=\"4\">朋友</option><option value=\"5\">紧急联系人</option><option value=\"6\">其他</option><option value=\"7\">父亲</option><option value=\"8\">母亲</option><option value=\"9\">子女</option><option value=\"10\">配偶</option></select></td>"
				: "<td><select id=\"r\" style=\"width: 150px;\"><option value=\"\">请选择</option><option value=\"1\">本人</option><option value=\"2\">亲属</option><option value=\"3\">同事</option><option value=\"4\">朋友</option><option value=\"5\">紧急联系人</option><option value=\"6\" selected>其他</option><option value=\"7\">父亲</option><option value=\"8\">母亲</option><option value=\"9\">子女</option><option value=\"10\">配偶</option></select></td>",
			"</tr>",
			"<tr>",
			"<td>联系号码：</td>",
			"<td>" + (callInfoObj.borrowNid == "book" ? callInfoObj.recordMobile : data[mType]) + "</td>",
			"</tr>",
			"<tr>",
			"<td>催收结果：</td>",
			"<td id='reTd'><select id=\"re\" style=\"width: 150px;\"><option value=\"\">请选择</option><option value=\"2\">投诉/死亡</option><option value=\"8\">空号/停机</option><option value=\"12\">无诚意还款</option><option value=\"13\">转告</option><option value=\"18\">有诚意还款/承诺还款</option><option value=\"19\">已还款</option><option value=\"20\">不转告/不认识客户</option><option value=\"21\">无人接听/拒接/关机</option></select></td>",
			"</tr>",
			"<tr>",
			"<td>承诺还款日期：</td>",
			"<td><input id='returnDate' style='width: 150px;'></td>",
			"</tr>",
			"<tr>",
			"<td>催收结果说明：</td>",
			"<td></td>",
			"</tr>",
			"<tr>",
			"<td colspan='2'><textarea cols='50' rows='5' name='remark' style='resize: none;margin-left: 20px;' placeholder='200个字符以内'></textarea></td>",
			"</tr>",
			"</table>",
			'<style type="text/css" rel="stylesheet">.notAllowed{cursor: not-allowed}</style>',
			"<script>",
			'layui.use("laydate", function(){',
			'var laydate = layui.laydate;',
			'laydate.render({',
			'elem: "#returnDate",',
			'position : "fixed"',
			'});',
			'});',
			'var setSelect = function (selectId,options,appendId) {',
			'var o = [];',
			'for (var k in options){',
			'o.push("<option value=\" + k + \">" + options[k] + "</option>");',
			'}',
			'var s = "<select id=\" + selectId + \" style=\'width: 150px;\'><option value>请选择</option>" + o.join("") + "</select>";',
			'$("#" + appendId).empty().append(s);',
			callInfoObj.borrowNid == "book" ? '$("#" + selectId).val(6)' : '',
			'};',
			// 'var getCallShip = function () {',
			// '$.httpUtil_POST("call/getCallShip", function (data) {',
			// 'log("催收关系 返回", data);',
			// 'setSelect("r",data,"rTd");',
			// '});',
			// '};',
			// 'var getCallResult = function () {',
			// '$.httpUtil_POST("call/getCallResult", function (data) {',
			// 'log("催收结果 返回", data);',
			// 'setSelect("re",data,"reTd");',
			// '});',
			// '};',
			'$(function(){',
			'$("#callTable tr td:first-child").css({"text-align":"right","width":"50%"});',
			'$("#callTable tr td:last-child").css({"text-align":"center"});',
			// 'getCallShip();',
			// 'getCallResult();',
			'});',
			"</script>"
		];
		return page.join("");
	}
	
	/**
	 * 字典翻译通话对象
	 * @param type
	 */
	var getContType = function (type) {
		if (type == "1") {
			return "紧急联系人";
		} else if (type == "2") {
			return "直系亲属";
		} else if (type == "3") {
			return "其他联系人";
		} else if (type == "4") {
			return "借款人";
		}
	}
	
	var isSuccessCall1 = function (data) {//判断拨号是否成功
		return data.result == "0" ? false : (data.result == "1" && data.Response != "error" ? true : false);
	}
	
	var isSuccessCall2 = function (data) {//判断挂断是否成功
		return data.result == "1" ? false : (data.result == "0" && data.Response != "error" ? true : false);
	}
	
	var isSuccessCall3 = function (data) {//判断弹屏或者获取录音否成功
		return data.result == "0" ? false : true;
	}
})();


